﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DataContexts.Supplier;
using System.Threading;

public partial class DoPayment : SearchBookingBasePage
{
    DataContexts.Booking.BookingDataContext bookingDB = new DataContexts.Booking.BookingDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadDetails(0);
            LoadPaymentOptions();
        }
    }

    private void LoadPaymentOptions()
    {
        var opts = from po in bookingDB.PaymentOptions
                   select po;
        ddlPaymentOptions.Items.Clear();
        ddlPaymentOptions.Items.Add(new ListItem("Choose Card...", "0"));
        foreach (var po in opts)
            ddlPaymentOptions.Items.Add(new ListItem(po.PayOptName + "(£" + po.Charges.Value.ToString(Constants.DECIMAL_FORMAT) + ")", po.PayOptionId.ToString()));

        //ddlPaymentOptions.SelectedValue = PaymentOptionId.ToString();
    }

    private void LoadDetails(int PaymentOptionId)
    {
        SearchQuery query = new SearchQuery
        {
            CountryId = CountryId,
            RegionId = RegionId,
            LocationId = LocationId,
            PickUpDate = PickUpDate,
            DropDate = DropDate,
            PickUpTime = PickUpTime,
            DropTime = DropTime,
            AdultCapacity = AdultCapacity,
            ChildrenCapacity = ChildrenCapacity,
            LuggageCapacity = LuggageCapacity,
            ACOption = ACOption,
            Transmission = Transmission,
            SupplierVehicleId = SupplierVehicleId,
            SupplierLocationVehicleId = SupplierLocationVehicleId,
            SupplierId = SupplierId
        };

        SearchResults results = query.Execute();
        if (results.Rows.Count == 1)
        {
            ResultRow row = results.Rows[0];

            Location location = supplierContext.Locations.FirstOrDefault(p => p.LocationId == LocationId);
            imgVehicleImage.ImageUrl = "VehicleImage.ashx?vid=" + row.Vehicle.SupplierVehicleId.ToString();
            lblVehicleCatDesc.Text = row.Vehicle.VehicleCategory + " - " + row.Vehicle.VehicleDescription;
            lblBookingDuration.Text = row.TripDays.ToString();
            lblPickUpLocation.Text = location.LocationName;
            lblStartDayDate.Text = PickUpDate.DayOfWeek.ToString() + ", " + PickUpDate.ToString(Constants.FULLDATE_FORMAT) + " " + PickUpTime;
            lblReturnLocation.Text = location.LocationName;
            lblEndDayDate.Text = DropDate.DayOfWeek.ToString() + ", " + DropDate.ToString(Constants.FULLDATE_FORMAT) + " " + DropTime;

            //lblRentalCost.Text = row.Total.Value.ToString(Constants.DECIMAL_FORMAT);

            decimal bookingFees = row.Total.Value - (row.Price.Value * row.TripDays.Value);
            decimal rentCost = row.Total.Value - bookingFees;
            lblRentalCost.Text = rentCost.ToString(Constants.DECIMAL_FORMAT);// row.Total.Value.ToString(Constants.DECIMAL_FORMAT);
            lblBookingFees.Text = bookingFees.ToString(Constants.DECIMAL_FORMAT);
            lblPayOnArrivalRentCost.Text = lblRentalCost.Text;

            decimal dTotal = row.Total.Value;

            if (row.Supplier.PayOnArrival.Value && PayOnArrival)
            {
                dTotal -= rentCost;
                trPayNowRentCost.Visible = false;
                trPayOnArrivalHead.Visible = true;
                trPayOnArrivalRentCost.Visible = true;
            }
            else
            {
                trPayNowRentCost.Visible = true;
                trPayOnArrivalHead.Visible = false;
                trPayOnArrivalRentCost.Visible = false;
            }

            //Pricing
            if (AvailInsurance)
            {
                SupplierLocationVehicle slv = supplierContext.SupplierLocationVehicles.FirstOrDefault(p => p.SupplierLocationVehicleId == row.SupplierLocationVehicleId);

                trInsuranceCost.Visible = true;
                lblInsuranceCost.Text = (slv.InsuranceSellPrice.Value * row.TripDays).ToString();
                dTotal += (slv.InsuranceSellPrice.Value * row.TripDays.Value);
            }
            else
            {
                trInsuranceCost.Visible = false;
            }

            if (AvailNavigator && row.Supplier.Navigator.Value)
            {
                trNavigatorCost.Visible = true;
                if (AvailNavWithFixPrice)
                {
                    lblNavigatorCost.Text = row.Supplier.NavFixRentSellPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    dTotal += row.Supplier.NavFixRentSellPrice.Value;
                }
                else
                {
                    lblNavigatorCost.Text = (row.Supplier.NavRentSellPrice.Value * row.TripDays).ToString();
                    dTotal += (row.Supplier.NavRentSellPrice.Value * row.TripDays.Value);
                }
            }
            else
            {
                trNavigatorCost.Visible = false;
            }

            if (chkAddDriver.Checked)
            {
                if (row.Supplier.AddDriveRentSellPrice.HasValue)
                {
                    lblAdditionalDriverCost.Text = row.Supplier.AddDriveRentSellPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    dTotal += row.Supplier.AddDriveRentSellPrice.Value;
                }
                else
                {
                    lblAdditionalDriverCost.Text = "0.00";
                }
            }

            if (PaymentOptionId > 0)
            {
                trCardCharges.Visible = true;
                btnPayNow.Enabled = true;
                DataContexts.Booking.PaymentOption po = bookingDB.PaymentOptions.FirstOrDefault(p => p.PayOptionId == PaymentOptionId);
                if (po != null)
                {
                    lblCardCharges.Text = po.Charges.Value.ToString(Constants.DECIMAL_FORMAT);
                    dTotal += po.Charges.Value;
                }
            }
            else
            {
                trCardCharges.Visible = false;
                btnPayNow.Enabled = false;
            }

            lblTotalBookingCost.Text = dTotal.ToString(Constants.DECIMAL_FORMAT);
        }
        else
        {
            Response.Redirect("/default.aspx");
        }
    }

    protected void btnPayNow_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            SearchQuery query = new SearchQuery
            {
                CountryId = CountryId,
                RegionId = RegionId,
                LocationId = LocationId,
                PickUpDate = PickUpDate,
                DropDate = DropDate,
                PickUpTime = PickUpTime,
                DropTime = DropTime,
                AdultCapacity = AdultCapacity,
                ChildrenCapacity = ChildrenCapacity,
                LuggageCapacity = LuggageCapacity,
                ACOption = ACOption,
                Transmission = Transmission,
                SupplierVehicleId = SupplierVehicleId,
                SupplierLocationVehicleId = SupplierLocationVehicleId,
                SupplierId = SupplierId
            };

            SearchResults results = query.Execute();
            if (results.Rows.Count == 1)
            {
                ResultRow row = results.Rows[0];

                Location location = supplierContext.Locations.FirstOrDefault(p => p.LocationId == LocationId);

                decimal dSellTotal = row.Total.Value;
                decimal dTotal = row.Price.Value * row.TripDays.Value;
                decimal dPayOnArrivalPrice = 0;
                decimal dPayNowPrice = dSellTotal;

                if (PayOnArrival && row.Supplier.PayOnArrival.Value)
                {
                    decimal bookingFees = row.Total.Value - (row.Price.Value * row.TripDays.Value);
                    dPayOnArrivalPrice = dPayNowPrice - bookingFees;
                    dPayNowPrice -= dPayOnArrivalPrice;
                }
                SupplierLocationVehicle slv = supplierContext.SupplierLocationVehicles.FirstOrDefault(p => p.SupplierLocationVehicleId == row.SupplierLocationVehicleId);

                //Pricing
                if (AvailInsurance)
                {
                    dSellTotal += slv.InsuranceSellPrice.Value * row.TripDays.Value;
                    dPayNowPrice += slv.InsuranceSellPrice.Value * row.TripDays.Value;
                    dTotal += slv.InsurancePrice.Value * row.TripDays.Value;
                }

                if (AvailNavigator && row.Supplier.Navigator.Value)
                {
                    if (AvailNavWithFixPrice)
                    {
                        dSellTotal += row.Supplier.NavFixRentSellPrice.Value;
                        dPayNowPrice += row.Supplier.NavFixRentSellPrice.Value;
                        dTotal += row.Supplier.NavFixRentPrice.Value;
                    }
                    else
                    {
                        dSellTotal += row.Supplier.NavRentSellPrice.Value * row.TripDays.Value;
                        dPayNowPrice += row.Supplier.NavRentSellPrice.Value * row.TripDays.Value;
                        dTotal += row.Supplier.NavRentPrice.Value * row.TripDays.Value;
                    }
                }

                if (chkAddDriver.Checked)
                {
                    dSellTotal += row.Supplier.AddDriveRentSellPrice.Value;
                    dPayNowPrice += row.Supplier.AddDriveRentSellPrice.Value;
                    dTotal += row.Supplier.AddDriveRentPrice.Value;
                }


                DataContexts.Booking.PaymentOption po = bookingDB.PaymentOptions.FirstOrDefault(p => p.PayOptionId == Convert.ToInt32(ddlPaymentOptions.SelectedValue));
                if (po != null)
                {
                    dTotal += po.Charges.Value;
                    dSellTotal += po.Charges.Value;
                    dPayNowPrice += po.Charges.Value;
                }

                DataContexts.Booking.Booking booking = new DataContexts.Booking.Booking
                {
                    TripDays = row.TripDays,
                    AvailInsurance = AvailInsurance,
                    AvailNavigator = AvailNavigator,
                    AvailNavFixRent = AvailNavWithFixPrice,
                    BookingDate = DateTime.Now,
                    DropDate = DropDate,
                    PickUpDate = PickUpDate,
                    DropTime = DropTime,
                    PickUpTime = PickUpTime,
                    GracePeriod = row.Supplier.GracePeriodMins.Value,
                    InsurancePrice = (AvailInsurance ? slv.InsurancePrice : 0),
                    InsuranceSellPrice = (AvailInsurance ? slv.InsuranceSellPrice : 0),
                    LocationId = LocationId,
                    NagivatorSellRentPrice = (AvailNavigator ? row.Supplier.NavRentSellPrice : 0),
                    NavigatorRentPrice = (AvailNavigator ? row.Supplier.NavRentPrice : 0),
                    TotalNavRentPrice = row.TripDays * (AvailNavigator ? row.Supplier.NavRentPrice : 0),
                    TotalNavSellRentPrice = row.TripDays * (AvailNavigator ? row.Supplier.NavRentSellPrice : 0),
                    NavFixRentPrice = (AvailNavWithFixPrice ? row.Supplier.NavFixRentPrice : 0),
                    NavFixSellRentPrice = (AvailNavWithFixPrice ? row.Supplier.NavFixRentSellPrice : 0),
                    RentSellPrice = row.SellPrice,
                    RentPrice = row.Price,
                    Status = 1,
                    SupplierId = SupplierId,
                    SupplierLocationVehicleId = SupplierLocationVehicleId,
                    SupplierVehicleId = SupplierVehicleId,
                    TotalRentPrice = row.Price * row.TripDays,
                    TotalRentSellPrice = row.SellPrice * row.TripDays,
                    TotalSellPrice = dSellTotal,
                    TotalPrice = dTotal,
                    PayNowPrice = dPayNowPrice,
                    PayOnArrivalPrice = dPayOnArrivalPrice,
                    PayOnArrival = PayOnArrival,
                    PayOptionId = po.PayOptionId,
                    CardCharges = po.Charges
                };

                #region User Mapping
                DataContexts.UserDataContext userDB = new DataContexts.UserDataContext();
                DataContexts.User user = userDB.Users.FirstOrDefault(p => p.Username == txtEmailAddress.Text);
                if (user == null)
                {
                    user = new DataContexts.User
                    {
                        Username = txtEmailAddress.Text,
                        Active = true,
                        UserType = Convert.ToInt32(Enums.UserTypes.Customer),
                        EmailAddress = txtEmailAddress.Text,
                        Password = RandomPassword.Generate()
                    };
                    userDB.Users.InsertOnSubmit(user);
                    userDB.SubmitChanges();
                }

                booking.UserId = user.UserId;
                #endregion


                bookingDB.Bookings.InsertOnSubmit(booking);
                bookingDB.SubmitChanges();

                booking.BookingReference = Helper.GetBookingReferenceNO(booking.BookingId);
                bookingDB.SubmitChanges();

                DataContexts.Booking.BookingDriver bookDriver = new DataContexts.Booking.BookingDriver
                {
                    BookingId = booking.BookingId,
                    EmailAddress = txtEmailAddress.Text,
                    FirstName = txtFirstName.Text,
                    LastName = txtLastName.Text,
                    Title = txtTitle.Text,
                    Phone = txtPhone.Text,
                    Mobile = txtMobile.Text,
                    Primary = true
                };

                bookingDB.BookingDrivers.InsertOnSubmit(bookDriver);

                if (chkAddDriver.Checked)
                {
                    DataContexts.Booking.BookingDriver bookAddDriver = new DataContexts.Booking.BookingDriver
                    {
                        BookingId = booking.BookingId,
                        EmailAddress = txtAddEmailAddress.Text,
                        FirstName = txtAddFirstName.Text,
                        LastName = txtAddLastName.Text,
                        Title = txtAddTitle.Text,
                        Phone = txtAddPhone.Text,
                        Mobile = txtAddMobile.Text,
                        Primary = false
                    };
                    bookingDB.BookingDrivers.InsertOnSubmit(bookAddDriver);
                }

                bookingDB.SubmitChanges();

                Response.Redirect("/thankyou.aspx");
            }
            else
            {
                Response.Redirect("/default.aspx");
            }
        }
    }
    protected void chkAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        tblAddDriver.Visible = chkAddDriver.Checked;
        trAddDriverCost.Visible = chkAddDriver.Checked;
        LoadDetails(Convert.ToInt32(ddlPaymentOptions.SelectedValue));
    }
    protected void ddlPaymentOptions_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadDetails(Convert.ToInt32(ddlPaymentOptions.SelectedValue));
    }
}
